// 代码格式化工具
class CodeFormatter {
    // 支持的语言配置
    static languages = {
        javascript: { name: 'JavaScript', extensions: ['js', 'jsx'], indent: 2 },
        typescript: { name: 'TypeScript', extensions: ['ts', 'tsx'], indent: 2 },
        python: { name: 'Python', extensions: ['py'], indent: 4 },
        java: { name: 'Java', extensions: ['java'], indent: 4 },
        csharp: { name: 'C#', extensions: ['cs'], indent: 4 },
        cpp: { name: 'C++', extensions: ['cpp', 'cxx', 'cc'], indent: 2 },
        c: { name: 'C', extensions: ['c', 'h'], indent: 2 },
        go: { name: 'Go', extensions: ['go'], indent: 1 }, // Go 使用 tab
        rust: { name: 'Rust', extensions: ['rs'], indent: 4 },
        php: { name: 'PHP', extensions: ['php'], indent: 4 },
        ruby: { name: 'Ruby', extensions: ['rb'], indent: 2 },
        swift: { name: 'Swift', extensions: ['swift'], indent: 4 },
        kotlin: { name: 'Kotlin', extensions: ['kt', 'kts'], indent: 4 },
        html: { name: 'HTML', extensions: ['html', 'htm'], indent: 2 },
        css: { name: 'CSS', extensions: ['css'], indent: 2 },
        scss: { name: 'SCSS', extensions: ['scss'], indent: 2 },
        json: { name: 'JSON', extensions: ['json'], indent: 2 },
        xml: { name: 'XML', extensions: ['xml'], indent: 2 },
        yaml: { name: 'YAML', extensions: ['yml', 'yaml'], indent: 2 },
        sql: { name: 'SQL', extensions: ['sql'], indent: 2 }
    };

    // 格式化代码
    static formatCode(code, language = 'javascript', options = {}) {
        try {
            if (!code || typeof code !== 'string') {
                return { success: false, error: '代码内容不能为空' };
            }

            const defaultOptions = {
                indentSize: this.languages[language]?.indent || 2,
                indentType: language === 'go' ? 'tab' : 'space',
                insertFinalNewline: true,
                trimTrailingWhitespace: true,
                maxLineLength: 100
            };

            const config = { ...defaultOptions, ...options };
            let formattedCode = code;

            // 基础格式化处理
            switch (language) {
                case 'javascript':
                case 'typescript':
                    formattedCode = this.formatJavaScript(code, config);
                    break;
                case 'python':
                    formattedCode = this.formatPython(code, config);
                    break;
                case 'java':
                case 'csharp':
                case 'cpp':
                case 'c':
                    formattedCode = this.formatCStyle(code, config);
                    break;
                case 'go':
                    formattedCode = this.formatGo(code, config);
                    break;
                case 'html':
                    formattedCode = this.formatHTML(code, config);
                    break;
                case 'css':
                case 'scss':
                    formattedCode = this.formatCSS(code, config);
                    break;
                case 'json':
                    formattedCode = this.formatJSON(code, config);
                    break;
                case 'xml':
                    formattedCode = this.formatXML(code, config);
                    break;
                case 'sql':
                    formattedCode = this.formatSQL(code, config);
                    break;
                default:
                    formattedCode = this.formatGeneric(code, config);
            }

            // 通用后处理
            if (config.trimTrailingWhitespace) {
                formattedCode = formattedCode.replace(/[ \t]+$/gm, '');
            }

            if (config.insertFinalNewline && !formattedCode.endsWith('\n')) {
                formattedCode += '\n';
            }

            // 统计信息
            const stats = {
                originalLines: code.split('\n').length,
                formattedLines: formattedCode.split('\n').length,
                originalSize: new Blob([code]).size,
                formattedSize: new Blob([formattedCode]).size
            };

            return {
                success: true,
                data: {
                    formatted: formattedCode,
                    original: code,
                    language: language,
                    stats: stats
                }
            };
        } catch (error) {
            return { success: false, error: `代码格式化失败: ${error.message}` };
        }
    }

    // JavaScript/TypeScript 格式化
    static formatJavaScript(code, options) {
        const indent = this.getIndentString(options);
        let formatted = code;
        let level = 0;

        // 简化的 JavaScript 格式化
        const lines = formatted.split('\n');
        const result = [];

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed) {
                result.push('');
                continue;
            }

            // 减少缩进的字符
            if (trimmed.match(/^[}\])]/) || trimmed.includes('} else {')) {
                level = Math.max(0, level - 1);
            }

            // 添加当前行
            result.push(indent.repeat(level) + trimmed);

            // 增加缩进的字符
            if (trimmed.match(/[{[\(]$/) || trimmed.includes('if (') || 
                trimmed.includes('for (') || trimmed.includes('while (') ||
                trimmed.includes('function') || trimmed.includes('=>')) {
                level++;
            }
        }

        return result.join('\n');
    }

    // Python 格式化
    static formatPython(code, options) {
        const indent = this.getIndentString(options);
        const lines = code.split('\n');
        const result = [];
        let level = 0;

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed || trimmed.startsWith('#')) {
                result.push(trimmed);
                continue;
            }

            // Python 缩进逻辑
            if (trimmed.match(/^(except|elif|else|finally)/) || 
                trimmed.match(/^(def|class|if|for|while|try|with).*:$/)) {
                if (trimmed.match(/^(except|elif|else|finally)/)) {
                    level = Math.max(0, level - 1);
                }
                result.push(indent.repeat(level) + trimmed);
                if (trimmed.endsWith(':')) {
                    level++;
                }
            } else {
                result.push(indent.repeat(level) + trimmed);
            }
        }

        return result.join('\n');
    }

    // C 风格语言格式化 (C, C++, Java, C#)
    static formatCStyle(code, options) {
        const indent = this.getIndentString(options);
        const lines = code.split('\n');
        const result = [];
        let level = 0;

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('/*')) {
                result.push(trimmed);
                continue;
            }

            // 减少缩进
            if (trimmed.startsWith('}') || trimmed === 'break;' || trimmed === 'continue;') {
                level = Math.max(0, level - 1);
            }

            result.push(indent.repeat(level) + trimmed);

            // 增加缩进
            if (trimmed.endsWith('{') || 
                (trimmed.includes('case ') && trimmed.endsWith(':')) ||
                trimmed === 'default:') {
                level++;
            }
        }

        return result.join('\n');
    }

    // Go 格式化
    static formatGo(code, options) {
        // Go 使用 tab 缩进
        const lines = code.split('\n');
        const result = [];
        let level = 0;

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed || trimmed.startsWith('//')) {
                result.push(trimmed);
                continue;
            }

            if (trimmed.startsWith('}')) {
                level = Math.max(0, level - 1);
            }

            result.push('\t'.repeat(level) + trimmed);

            if (trimmed.endsWith('{') || 
                (trimmed.includes('case ') && trimmed.endsWith(':')) ||
                trimmed === 'default:') {
                level++;
            }
        }

        return result.join('\n');
    }

    // HTML 格式化
    static formatHTML(code, options) {
        const indent = this.getIndentString(options);
        let formatted = code;
        let level = 0;

        // 简单的 HTML 格式化
        formatted = formatted.replace(/></g, '>\n<');
        const lines = formatted.split('\n');
        const result = [];

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed) continue;

            // 自闭合标签或注释
            if (trimmed.match(/^<[^>]+\/>$/) || 
                trimmed.match(/^<!--.*-->$/)) {
                result.push(indent.repeat(level) + trimmed);
                continue;
            }

            // 结束标签
            if (trimmed.match(/^<\/[^>]+>$/)) {
                level = Math.max(0, level - 1);
                result.push(indent.repeat(level) + trimmed);
                continue;
            }

            // 开始标签
            result.push(indent.repeat(level) + trimmed);
            if (trimmed.match(/^<[^>\/]+>/) && 
                !trimmed.match(/<(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)/)) {
                level++;
            }
        }

        return result.join('\n');
    }

    // CSS 格式化
    static formatCSS(code, options) {
        const indent = this.getIndentString(options);
        let formatted = code;
        let level = 0;

        // CSS 基础格式化
        formatted = formatted.replace(/\{/g, ' {\n');
        formatted = formatted.replace(/\}/g, '\n}\n');
        formatted = formatted.replace(/;/g, ';\n');
        
        const lines = formatted.split('\n');
        const result = [];

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed) continue;

            if (trimmed === '}') {
                level = Math.max(0, level - 1);
                result.push(indent.repeat(level) + trimmed);
            } else if (trimmed.endsWith('{')) {
                result.push(indent.repeat(level) + trimmed);
                level++;
            } else if (trimmed.endsWith(';') || trimmed.startsWith('@')) {
                result.push(indent.repeat(level) + trimmed);
            } else {
                result.push(indent.repeat(level) + trimmed);
            }
        }

        return result.join('\n');
    }

    // JSON 格式化
    static formatJSON(code, options) {
        try {
            const parsed = JSON.parse(code);
            return JSON.stringify(parsed, null, options.indentSize);
        } catch (error) {
            throw new Error('无效的 JSON 格式');
        }
    }

    // XML 格式化
    static formatXML(code, options) {
        const indent = this.getIndentString(options);
        let formatted = code;
        let level = 0;

        // 基础 XML 格式化
        formatted = formatted.replace(/></g, '>\n<');
        const lines = formatted.split('\n');
        const result = [];

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed) continue;

            if (trimmed.match(/^<\/[^>]+>$/)) {
                level = Math.max(0, level - 1);
                result.push(indent.repeat(level) + trimmed);
            } else if (trimmed.match(/^<[^>\/]+\/>$/)) {
                result.push(indent.repeat(level) + trimmed);
            } else if (trimmed.match(/^<[^>\/]+>$/)) {
                result.push(indent.repeat(level) + trimmed);
                level++;
            } else {
                result.push(indent.repeat(level) + trimmed);
            }
        }

        return result.join('\n');
    }

    // SQL 格式化
    static formatSQL(code, options) {
        const indent = this.getIndentString(options);
        const keywords = [
            'SELECT', 'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN',
            'GROUP BY', 'HAVING', 'ORDER BY', 'INSERT INTO', 'UPDATE', 'DELETE FROM',
            'CREATE', 'ALTER', 'DROP', 'VALUES', 'SET', 'ON', 'AND', 'OR'
        ];

        let formatted = code.toUpperCase();

        // 在关键字前添加换行
        keywords.forEach(keyword => {
            const regex = new RegExp(`\\b${keyword}\\b`, 'gi');
            formatted = formatted.replace(regex, `\n${keyword}`);
        });

        const lines = formatted.split('\n');
        const result = [];
        
        for (let line of lines) {
            const trimmed = line.trim();
            if (trimmed) {
                result.push(trimmed);
            }
        }

        return result.join('\n');
    }

    // 通用格式化
    static formatGeneric(code, options) {
        const indent = this.getIndentString(options);
        const lines = code.split('\n');
        const result = [];
        let level = 0;

        for (let line of lines) {
            const trimmed = line.trim();
            if (!trimmed) {
                result.push('');
                continue;
            }

            // 简单的大括号缩进
            if (trimmed.startsWith('}') || trimmed.startsWith(']') || trimmed.startsWith(')')); {
                level = Math.max(0, level - 1);
            }

            result.push(indent.repeat(level) + trimmed);

            if (trimmed.endsWith('{') || trimmed.endsWith('[') || trimmed.endsWith('(')) {
                level++;
            }
        }

        return result.join('\n');
    }

    // 生成缩进字符串
    static getIndentString(options) {
        return options.indentType === 'tab' ? '\t' : ' '.repeat(options.indentSize);
    }

    // 压缩代码
    static minifyCode(code, language) {
        try {
            let minified = code;

            // 移除注释和多余空白
            switch (language) {
                case 'javascript':
                case 'typescript':
                case 'java':
                case 'csharp':
                case 'cpp':
                case 'c':
                    // 移除单行注释
                    minified = minified.replace(/\/\/.*$/gm, '');
                    // 移除多行注释
                    minified = minified.replace(/\/\*[\s\S]*?\*\//g, '');
                    break;
                case 'python':
                    // 移除 Python 注释
                    minified = minified.replace(/#.*$/gm, '');
                    break;
                case 'html':
                    // 移除 HTML 注释
                    minified = minified.replace(/<!--[\s\S]*?-->/g, '');
                    break;
                case 'css':
                    // 移除 CSS 注释
                    minified = minified.replace(/\/\*[\s\S]*?\*\//g, '');
                    break;
            }

            // 移除多余的空白字符
            minified = minified.replace(/\n\s*\n/g, '\n'); // 移除空行
            minified = minified.replace(/^\s+|\s+$/gm, ''); // 移除行首行尾空白
            minified = minified.split('\n').filter(line => line.trim()).join('\n');

            return {
                success: true,
                data: {
                    minified: minified,
                    original: code,
                    stats: {
                        originalSize: new Blob([code]).size,
                        minifiedSize: new Blob([minified]).size,
                        compressionRatio: ((new Blob([code]).size - new Blob([minified]).size) / new Blob([code]).size * 100).toFixed(2)
                    }
                }
            };
        } catch (error) {
            return { success: false, error: `代码压缩失败: ${error.message}` };
        }
    }

    // 检测代码语言
    static detectLanguage(code, filename = '') {
        // 通过文件扩展名检测
        if (filename) {
            const ext = filename.split('.').pop()?.toLowerCase();
            for (const [lang, config] of Object.entries(this.languages)) {
                if (config.extensions.includes(ext)) {
                    return lang;
                }
            }
        }

        // 通过代码特征检测
        if (code.includes('<?php') || code.includes('<?=')) return 'php';
        if (code.includes('<!DOCTYPE html>') || code.includes('<html>')) return 'html';
        if (code.includes('def ') && code.includes(':')) return 'python';
        if (code.includes('function') && code.includes('{')) return 'javascript';
        if (code.includes('public class') || code.includes('private ')) return 'java';
        if (code.includes('#include') && code.includes('<iostream>')) return 'cpp';
        if (code.includes('package main') && code.includes('func ')) return 'go';

        return 'javascript'; // 默认语言
    }

    // 获取语言列表
    static getLanguages() {
        return {
            success: true,
            data: Object.entries(this.languages).map(([key, config]) => ({
                key,
                name: config.name,
                extensions: config.extensions
            }))
        };
    }
}